package com.mbigger.redis;

import com.mbigger.redis.redis.MessageReceiver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

/**
 * Hello world!
 *
 */
@SpringBootApplication
public class SpringBootdRedisApplication {

    public static final  String channel = "testchannel";
    public static final  String channel2 = "chat";

    public static void main(String[] args) {
        SpringApplication.run(SpringBootdRedisApplication.class, args);
    }

    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                            MessageListenerAdapter listenerAdapter, MessageListenerAdapter listenerAdapter2) {

        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        //订阅了一个叫testchannel 的通道
        container.addMessageListener(listenerAdapter, new PatternTopic(SpringBootdRedisApplication.channel));
        //订阅了一个叫chat的频道
        container.addMessageListener(listenerAdapter2, new PatternTopic(SpringBootdRedisApplication.channel2));
        return container;
    }

    /**
     * 消息监听器适配器，绑定消息处理器，利用反射技术调用消息处理器的业务方法
     * @param receiver
     * @return
     */
    @Bean
    MessageListenerAdapter listenerAdapter(MessageReceiver receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage");
    }

    @Bean
    MessageListenerAdapter listenerAdapter2(MessageReceiver receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage2");
    }
}
